package com.xiaok.netty.client.initializer;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoop;
import io.netty.channel.nio.NioEventLoopGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;
import java.util.concurrent.TimeUnit;

/**
 * @Classname ClientStart
 * @Description TODO
 * @Date 2020/10/8 17:05
 * @Created by xiaok
 * ApplicationContextInitializer 在 @Configuration 之前
 */
@Component("tcpClient")
public class TCPClient {
    public Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    @Qualifier("clientBootstrap")
    private Bootstrap bootstrap;
    @Autowired
    @Qualifier("tcpSocketAddress")
    private InetSocketAddress inetSocketAddress;
    @Autowired
    @Qualifier("clientLoopGroup")
    private NioEventLoopGroup group;

    public void run()   {
        try {
          ChannelFuture channelFuture = bootstrap.connect(inetSocketAddress).addListener((ChannelFuture futureListener) -> {
                if (!futureListener.isSuccess()) {
                    log.info("连接服务器失败，5s后重新尝试连接！");
                    futureListener.channel().eventLoop().schedule(() -> { //连接服务器失败，5s后重新尝试连接！
                        run();
                    }, 5, TimeUnit.SECONDS);
                }else if (futureListener.isSuccess()){
                    log.info("连接服务器成功!！");
                }
            });
            channelFuture.channel().closeFuture().sync();

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            log.info("客户端优雅的关闭服务");
            group.shutdownGracefully();
        }
    }
}
